package com.jn.rxjava.presenter;

import android.content.Context;

import com.jn.rxjava.contract.MusicContract;
import com.jn.rxjava.entity.MusicEntity;
import com.jn.rxjava.service.MusicService;
import com.jn.rxjava.utils.LogUtils;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class MusicPresenter implements MusicContract.IMusicPresenter {
    private MusicContract.IMusicView mMainView;
    private Context mContext;

    public MusicPresenter(MusicContract.IMusicView mMainView, Context mContext) {
        this.mMainView = mMainView;
        this.mContext = mContext;
    }

    @Override
    public void getData(String keyWord, int... n) {//post 同步
        LogUtils.d("asdf", "keyWord == " + keyWord);
        String url = "https://api.cenguigui.cn/api/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        MusicService musicService = retrofit.create(MusicService.class);

        musicService.getData(keyWord)
                .observeOn(AndroidSchedulers.mainThread())// 指定 最后拿到数据操，解析，显示发生在主线程
                .subscribeOn(Schedulers.io())// 指定 网络请求耗时操作发生在子线程;
                .subscribe(new Observer<MusicEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull MusicEntity musicEntity) {
                        if (mMainView != null) {
                            mMainView.showData(musicEntity);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
